var dbConfig = require('../../util/dbconfig');
var moment = require('moment');
const fs = require("fs");
const path = require("path");
const formidable = require('formidable');
//添加地址(ok)
Addaddress= async (req, res) => {
	let sql =
		`insert into address(pid,content,createtime) value(?,?,?)`;
		var date = moment().format("YYYY-MM-DD HH:mm:ss");
	let sqlArr = [req.user.userName,JSON.stringify(req.body),date];
	var cb = async (err, data) => {
		if (err) {
			res.send({
				"text": "函数错误,Addaddress",
				"code": 500
			});
		} else {
			res.send({
				"data": data,
				"code": 200,
				"text": "地址添加成功"
			})
		}
	}
	dbConfig.sqlConnection(sql, sqlArr, cb)
}
Getaddress= async (req, res) => {
	let sql =
		`select * from address where pid='${req.user.userName}'`;
	let sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.send({
				"text": "函数错误,Getaddress",
				"code": 500
			});
		} else {
			res.send({
				"data": data,
				"code": 200,
				"text": "地址查询成功"
			})
		}
	}
	dbConfig.sqlConnection(sql, sqlArr, cb)
}
GetOneaddress= async (req, res) => {
	let sql =
		`select * from address where id='${req.query.id}'`;
	let sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.send({
				"text": "函数错误,GetOneaddress",
				"code": 500
			});
		} else {
			res.send({
				"data": data[0],
				"code": 200,
				"text": "地址查询成功"
			})
		}
	}
	dbConfig.sqlConnection(sql, sqlArr, cb)
}
Deladdress= async (req, res) => {
	let sql =
		`delete  from address where id='${req.body.params.id}'`
	let sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.send({
				"text": "函数错误,Deladdress",
				"code": 500
			});
		} else {
			res.send({
				"code": 200,
				"text": "地址删除成功"
			})
		}
	}
	dbConfig.sqlConnection(sql, sqlArr, cb)
}
Updateaddress= async (req, res) => {
	var date = moment().format("YYYY-MM-DD HH:mm:ss");
	var data = JSON.stringify(req.body) 
	let sql = `update address set createtime='${date}',content='${data}' where id=${req.body.id}`;
	let sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.send({
				"text": "函数错误,Updateaddress",
				"code": 500
			});
		} else {
			res.send({
				"code": 200,
				"text": "地址更新成功"
			})
		}
	}
	dbConfig.sqlConnection(sql, sqlArr, cb)
}
UpdataOrder= async (req, res) => {
	var base = req.body.data.items
	var contact = req.body.data.contact;
	var date = moment().format("YYYY-MM-DD HH:mm:ss");
	let sql = `insert into order_list(pid,content,contact,create_time) value('${req.user.userName}','${JSON.stringify(base)}','${JSON.stringify(contact)}','${date}')`;
	let sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.send({
				"text": "函数错误,UpdataOrder",
				"code": 500
			});
		} else {
			base.forEach(el=>{
				RudecuNum(el.id)
				AddNum(el.id)
			})
			res.send({
				"code": 200,
				"text": "生成订单成功"
			})
		}
	}
	dbConfig.sqlConnection(sql, sqlArr, cb)
}
//数量自减方法
function RudecuNum(id){
	var sql = `UPDATE things SET num=(num-1) WHERE (id=?)`
	var sqlArr = [id];
	return dbConfig.SySqlConnect(sql, sqlArr);
}
// 买数量自增
function AddNum(id){
	var sql = `UPDATE things SET buynum=(buynum+1) WHERE (id=?)`
	var sqlArr = [id];
	return dbConfig.SySqlConnect(sql, sqlArr);
}

SearChData= async (req, res) => {
	let sql = `select * from things where name like "%${req.query.query}%"`;
	let sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.send({
				"text": "函数错误,SearChData",
				"code": 500
			});
		} else {
			res.send({
				'data':data,
				"code": 200,
				"text": "搜索数据成功"
			})
		}
	}
	dbConfig.sqlConnection(sql, sqlArr, cb)
}
detailInfo= async (req, res) => {
	let sql = `select id,user_id,Introduction,nickname,img_url,sex from users where user_id='${req.user.userName}'`;
	let sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.send({
				"text": "函数错误,detailInfo",
				"code": 500
			});
		} else {
			res.send({
				'data':data[0],
				"code": 200,
				"text": "查询数据成功"
			})
		}
	}
	dbConfig.sqlConnection(sql, sqlArr, cb)
}
updateInfo= async (req, res) => {
	let base = req.body; 
	var sql = `UPDATE users SET nickname='${base.nickname}',sex='${base.sex}',Introduction='${base.Introduction}',img_url='${base.img_url}' WHERE id='${base.id}'`
	let sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.send({
				"text": "函数错误,updateInfo",
				"code": 500
			});
		} else {
			res.send({
				"code": 200,
				"text": "修改数据成功"
			})
		}
	}
	dbConfig.sqlConnection(sql, sqlArr, cb)
}
updateImg = (req, res) => {
	var form = new formidable.IncomingForm();
	form.encoding = 'utf-8';
	form.uploadDir = path.join((path.resolve(__dirname, '../../') + "/public/images"));
	form.keepExtensions = true; //保留后缀
	form.maxFieldsSize = 2 * 1024 * 1024;
	//处理图片
	form.parse(req, function(err, fields, files) {
		var filename = files.file.path;
		var nameArray = filename.split('.');
		var type = nameArray[nameArray.length - 1];
		var name = '';
		for (var i = 0; i < nameArray.length - 1; i++) {
			name = name + nameArray[i];
		}
		var d = new Date();
		var m = d.getMinutes();
		var s = d.getSeconds();
		m = checkTime(m);
		s = checkTime(s);

		function checkTime(i) {
			if (i < 10) {
				i = "0" + i
			}
			return i
		}
		var time = d.getFullYear() + '_' + (d.getMonth() + 1) + '_' + d.getDate() + '_' + d.getHours() + '_' + m + '_' + s ;
		var avatarName = name + time + '.' + type;
		var newPath = avatarName;
		fs.renameSync(files.file.path, newPath); //重命名
		newPath = newPath.split("images\\");
		res.send({
			data:"/public/images/"+newPath[1],
			text: '上传成功',
			code: 200
		})
	})
}
getOrderList= async (req, res) => {
	let sql = `select * from order_list where pid='${req.user.userName}'`;
	let sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.send({
				"text": "函数错误,getOrderList",
				"code": 500
			});
		} else {
			data.forEach(el=>{
				el.content = JSON.parse(el.content)
				el.contact = JSON.parse(el.contact)
			})
			res.send({
				'data':data,
				"code": 200,
				"text": "查询数据成功"
			})
		}
	}
	dbConfig.sqlConnection(sql, sqlArr, cb)
}

getOneOrderDeatil= async (req, res) => {
	let sql = `select * from order_list where id='${req.query.id}'`;
	let sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.send({
				"text": "函数错误,getOneOrderDeatil",
				"code": 500
			});
		} else {
			data.forEach(el=>{
				el.content = JSON.parse(el.content)
				el.contact = JSON.parse(el.contact)
			})
			res.send({
				'data':data[0],
				"code": 200,
				"text": "查询数据成功"
			})
		}
	}
	dbConfig.sqlConnection(sql, sqlArr, cb)
}


cateList = async (req, res) => {
	if (req.query.page >= 1) { //分页器查询数据库
		req.query.page = (req.query.page - 1) * req.query.size
	}
	//order by browsenum desc
	var sql = `select * from things where name like "%${req.query.query}%" order by browsenum desc  LIMIT ${req.query.page},${req.query.size} `;
	var sqlArr = [];
	let number;
	let result  =(await sortMoney(req))
	var cb = (err, data) => {
		var back={}
		back.money = result
		back.buynum = data
		res.send({
			"data": back,
			"code": 200,
			"text": "数据获取成功"
		})
	}
	dbConfig.sqlConnection(sql, sqlArr, cb)
}
function sortMoney(req){
	var sql = `select * from things where name like "%${req.query.query}%" order by price desc LIMIT ${req.query.page},${req.query.size} `;
	var sqlArr = [];
	return dbConfig.SySqlConnect(sql, sqlArr);
}
productHistory= async (req, res) => {
	var base = req.body
	var date = moment().format("YYYY-MM-DD HH:mm:ss");
	let sql = `insert into history(pid,content,create_time) value('${req.user.userName}','${JSON.stringify(base)}','${date}')`;
	let sqlArr = [];
	var cb = async (err, data) => {
		if (err) {
			res.send({
				"text": "函数错误,productHistory",
				"code": 500
			});
		} else {
			AddHistoryNum(base.id)
			res.send({
				"code": 201,
			})
		}
	}
	dbConfig.sqlConnection(sql, sqlArr, cb)
}
// 浏览数量自增
function AddHistoryNum(id){
	var sql = `UPDATE things SET browsenum=(browsenum+1) WHERE (id=?)`
	var sqlArr = [id];
	return dbConfig.SySqlConnect(sql, sqlArr);
}
getHistory = async (req, res) => {
	var sql = `select * from history where pid='${req.user.userName}'`;
	var sqlArr = [];
	var cb = (err, data) => {
		data.forEach(el=>{
			el.content = JSON.parse(el.content)
		})
		res.send({
			"data": data,
			"code": 200,
			"text": "数据获取成功"
		})
	}
	dbConfig.sqlConnection(sql, sqlArr, cb)
}
delHistory = async (req, res) => {
	var sql = `delete  from history where pid='${req.user.userName}'`;
	var sqlArr = [];
	var cb = (err, data) => {
		res.send({
			"code": 200,
			"text": "数据删除成功"
		})
	}
	dbConfig.sqlConnection(sql, sqlArr, cb)
}
module.exports = {
	Addaddress,
	Deladdress,
	Updateaddress,
	Getaddress,
	GetOneaddress,
	UpdataOrder,
	SearChData,
	detailInfo,
	updateInfo,
	updateImg,
	getOrderList,
	getOneOrderDeatil,
	cateList,
	productHistory,
	getHistory,
	delHistory
}
